// --------------------------------------------------------------------
//   name 	: 
//   desc 	: 
//   version 	: 
//   dev 	: 
// --------------------------------------------------------------------
// DEPENDENCIES
// 
// --------------------------------------------------------------------
// CHANGE HISTORY
// 0.1 	Initial Release
// --------------------------------------------------------------------
	plugins.quickattack = { // Add quick attacks to the village info page
		'get_unit_html' : function(unit, rallypoint) {
			return(
   "<a href=\"javascript:popup('popup_unit.php?unit="+unit.name+"', 520, 520)\">"+
					"<img src=\"graphic/unit/unit_"+unit.name+".png\" title=\""+unit.title+"\" alt=\"\"/></a>" +
					"<input type=\"text\" value=\"\" tabindex=\""+(unit.index+1)+"\" size=\"5\" name=\""+unit.name+"\"/>" +
					"<a href=\"javascript:insertUnit(document.forms[0]."+unit.name+", "+rallypoint.units[unit.index]+")\">"+
					"("+rallypoint.units[unit.index]+")</a>");
		},

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    'get_rallypoint_html' : function(village_id,x,y) {
	  var rallypoints = getValue("rallypoints");
	  var rallypoint = rallypoints[village_id];
	  if(!rallypoint) return false;

	  var html = "<h4>Quick Attack</h4><form name=\"units\" action=\"game.php?village="+personals.getCurrentVillage()+"&amp;screen=place&amp;try=confirm\" method=\"post\">\n";

	  html += "<table>\n<tbody><tr>\n";
	  var i=0;
	  var units = plugins.quickattack.getUnits();
	  html += "<td valign=\"top\" width=\"150\"><table class=\"vis\" width=\"100%\"><tbody>";
	  var col=0;
	  for(var i in units) {
		  var unit = units[i];
		  if(unit.col != col) {
			  html += "</tbody></table></td>\n";
			  html += "<td valign=\"top\" width=\"150\"><table class=\"vis\" width=\"100%\"><tbody>";
			  col = unit.col;
		  }
		  html += "<tr><td>"+plugins.quickattack.get_unit_html(unit, rallypoint)+"\n</td></tr>";
	  }
	  html += "</tbody></table></td>\n";

	  html += "<table><tbody><tr>\n<td rowspan=\"2\">\n";
	  html += "x: <input type=\"text\" size=\"5\" value=\""+x+"\" name=\"x\"/>\n";
	  html += "y: <input type=\"text\" size=\"5\" value=\""+y+"\" name=\"y\"/>\n";
	  html += "</td>\n";
		//by using visibility: hidden we still get the gap so that it's the same layout as on the rallypoint
	  html += "<td align=\"top\" style=\"visibility:hidden;\"><a href=\"javascript:popup_scroll('targets.php?village="+personals.getCurrentVillage()+"&amp;mode=own', 340, 400)\">Your own</a></td>\n";
	  html += "<td rowspan=\"2\"><input class=\"attack\" name=\"attack\" value=\"Attack\" style=\"font-size: 10pt;\" type=\"submit\"></td>\n";
	  html += "<td rowspan=\"2\"><input class=\"support\" name=\"support\" value=\"Support\" style=\"font-size: 10pt;\" type=\"submit\"></td>\n";
	  html += "</tr></tbody></table>";
	  html += "</form>";
	  return html;
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
  	//report enhancer by jim5272 http://twenhancer.freeforums.org/report-enhancement-t16.html
  enhance_game_report : function() {
	  var allTR, ResourceParent, allSpans, thisSpan, thisSpansParent, origHtml, newHtml, resourceArray;
	  var resourceTotal, cavReturn;
	  
	  cavReturn = 0;
	  resourceTD = $('td:has(> img[src$="graphic/holz.png"])')[0];
	  if(!resourceTD) return;
	  newHtml = resourceTD.innerHTML.replace(/<span.*?<\/span>/g,""); // remove spans
	  newHtml = newHtml.replace(/<img.*?>/g,""); // remove images
	  resourceArray = newHtml.split(" ");
	  resourceTotal = 0.0;
	  if(resourceArray.length){
		  for (var i = 0; i < 3; i++){
			  resourceTotal += (resourceArray[i].valueOf() * 1);
		  }
	  }
	  if (resourceTotal != 0){
		  cavReturn = resourceTotal / 80;
		  cavReturn = Math.ceil(cavReturn);
	  }
		
	  resourceTD.innerHTML += "&nbsp;&nbsp;<b>Total:</b><img src=\"/graphic/res.png\" title=\"Total Available\" alt=\"\"> " + resourceTotal + "&nbsp;<a href=\"javascript:insertUnit(document.forms[0].light, "+cavReturn+")\"><img src=\"graphic/unit/unit_light.png\" title=\"LC to return total\" alt=\"\">&nbsp;" + cavReturn+"</a>";

	  var enemy = xpathGetFirst("/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[3]/td/table[4]/tbody/tr[2]/td[2]/a").innerHTML;
	  var enemy_x = enemy.replace(/(.+)\((-?\d+)\|(-?\d+)\)(?: (K\d+))?/gi,"$2");
	  var enemy_y = enemy.replace(/(.+)\((-?\d+)\|(-?\d+)\)(?: (K\d+))?/gi,"$3");
	  
	  
	  xpathGetFirst("/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[2]/table").width='';
	  xpathGetFirst("//td[@height='160']").innerHTML += plugins.quickattack.get_rallypoint_html(personals.getCurrentVillage(),enemy_x,enemy_y);
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    getUnits : function() {
	  if(!plugins.quickattack._units)
	  plugins.quickattack._units = getValue("units");
	  return plugins.quickattack._units;
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    enhance_game_place : function() {
	  if(/try=confirm/.test(location.href) || /mode=(?:units|sim)/.test(location.href)) return;
	  var units = [];
	  var unitsObj = {};
	  var rallypoint = [];
	  col=0;
	  $("form > table:first tr:first > td").each(function() {
		  $("table tr td", this).each(function() {
			  var title = $(this).find("img")[0].title;
			  var input = $(this).find("input")[0];
				//name = uneval(name);
				//var name = this;
				//var tmp = this.innerHTML.match(//);
			  var unit = {name:input.name,index:(input.tabIndex-1),title:title,col:col};
			  units.push(unit);
			  unitsObj[input.name] = unit;

			  var unitcount = $(this).find("a:last")[0].innerHTML.replace(/\(|\)/g,'');

			  rallypoint.push(unitcount);
		  });
		  col++;
	  });

		// add haul data
	  unitsObj.spear.booty=25;
	  unitsObj.sword.booty=15;
	  unitsObj.axe.booty=10;
	  if(unitsObj.archer) unitsObj.archer.booty=10;
	  unitsObj.spy.booty=0;
	  unitsObj.light.booty=80;
	  if(unitsObj.marcher) unitsObj.marcher.booty=50;
	  unitsObj.heavy.booty=50;
	  unitsObj.ram.booty=0;
	  if(unitsObj.knight) unitsObj.knight.booty=100;
	  unitsObj.snob.booty=0;

	  setValue("units", units);

	  log(3, uneval(units));

		//log(3, uneval(rallypoint));

		//from TW's script.js
	  var getTime = function(element) {
			// Zeit auslesen
		  if(element.firstChild.nodeValue == null) return -1;
		  part = element.firstChild.nodeValue.split(":");

			// FÃƒÂ¼hrende Nullen entfernen
		  for(j=1; j<3; j++) {
			  if(part[j].charAt(0) == "0")
			  part[j] = part[j].substring(1, part[j].length);
		  }

			// Zusammenfassen
		  hours = parseInt(part[0]);
		  minutes = parseInt(part[1]);
		  seconds = parseInt(part[2]);
		  time = hours*60*60+minutes*60+seconds;
		  return parseInt(time);
	  }

	  var now = new Date().getTime();
	  var all = xpathGetAll("//span[@class='timer']",document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);
	  var span=false;
		// Find returning troops
	  for(var i=0;i<all.length;i++) {
		  span=all[i];
		  if(/^Return/.test(all.innerHTML)) break;
		  span=false;
	  }
	  var expires;
	  if(span) {
	  } else if(!span && all.length>0) {
		  span = all[0];
			// set expiry to twice the attack time to allow for return.
			// We don't know how long they've been traveling already
			// so just guess that it's twice the remaining attack time
		  expires = now + getTime(span)*1000;
	  } else {
		  expires = 0;
	  }

	  var rallypoints = getValue("rallypoints");
	  if(!rallypoints) rallypoints = new Object();
	  rallypoints[personals.getCurrentVillage()] = {'units':rallypoint,'timestamp':now,'expires':expires};
	  setValue("rallypoints", rallypoints);
	//  $('table.main table.vis:last').after(plugins.quickattack.get_overview());
	  $('table.main table:last').after(plugins.quickattack.get_overview());
//	  xpathGetFirst("/html/body/table[3]/tbody/tr/td/table[2]/tbody/tr/td[2]").innerHTML += plugins.quickattack.get_overview();

	  $("form > table:first tr:first table input").change(function() {
		  total=0;
		  $("form > table:first tr:first table input").each(function() {
			  var units = plugins.quickattack.getUnits();
			  unit = units[this.tabIndex-1];
			  if(this.value=='') return;
			  total += parseInt(this.value)*unit.booty;
		  });
		  log(3, total);
	  });
	  setFunc('insertUnit', function insertUnit(input, count) {
		  if(input.value != count)
		  input.value=count;
		  else
			  input.value='';
		  var evt = document.createEvent("HTMLEvents");
		  evt.initEvent("change", true, true);
		  input.dispatchEvent(evt);
	  });
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    'get_overview_heading' : function() {
	  var html = "";
	  var units = plugins.quickattack.getUnits();
	  for(var i=0;i<units.length;i++) {
		  var unit = units[i];
		  html += "<th width=\"35\"><img src=\"graphic/unit/unit_"+unit.name+".png\" title=\""+unit.title+"\" alt=\"\"></th>\n";
	  }
	  return html;
  },

// --------------------------------------------------------------------
// Function : Get Overview of all villages.
// --------------------------------------------------------------------
    'get_overview' : function() {
		//// add rallypoint overview
	  var rallypoints = getValue("rallypoints");

	  var html="<br><tr><td>";
	  html += "<hr><h3>Rallypoint overview</h3>";
	  html += "<table border=1 width=800 class=\"vis\"><tr><th>Village name</th>\n";
	  html += plugins.quickattack.get_overview_heading();
	  html += "<th width=10%>Updated</th>";
	  html += "<th width=10%>Expires</th>";
	  html += "</tr>";

	  var now = new Date().getTime();
	  TW_Villages = twe.myVillages();
	  var count = 0;
	  for(var i in TW_Villages) {
		  var v = TW_Villages[i];
		  var rallypoint = rallypoints[v.id];
		//  log(1,uneval(rallypoint));
		  out = (v.alias != '') ? v.alias : v.name;
		  if (out!=null) {
		  if (count%2 == 0) { style = ' class="odd"'; } else { style = ''; }
		  html += "<tr"+style+"><td><a href=\"javascript:location.href=location.href.replace(/village=([^&]+)/, 'village=" + v.id+"')\">"+out+"</a></td>";
		  if(!rallypoint) {
			  html+="<td colspan=\"14\">No data</td></tr>";
			//  continue;
		  } else {
		  html += plugins.quickattack.get_overview_row(v.id);
		  html += "<td>"+Math.round(((now-rallypoint.timestamp)/1000)/60)+" min ago</td>";
		  if(rallypoint.expires === 0) {
			  html += "<td></td>";
		  } else {
			  html += "<td>In "+Math.round(((rallypoint.expires-now)/1000)/60)+" min</td>";
		  }
		  }
		  html += "</tr>\n";
		  count++;
		  } // if(out!=null)
	  }
	  html += "</tr>";
	  html += "</table>\n<hr></td></tr>";
	  return html;
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    'get_overview_row' : function(vid) {
	  var rallypoints = getValue("rallypoints");
	  var rallypoint = rallypoints[vid];
	  if(!rallypoint) return "<td colspan=\"0\" align=\"center\">no data</td></tr>";

	  var arr = rallypoint.units;
	  var html = "";
	  for(var j=0;j<arr.length;j++) {
		  html += "<td>"+arr[j]+"</td>";
	  }
	  return html;
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
    'enhance_game_info_village' : function() {
	  var tbls = $("table");
	  var tmp = [];
	  for(kk=0; kk<tbls.length; kk++){
		  if(tbls[kk].getAttribute("class") == "vis"){
			  tmp = tbls[kk].innerHTML.match( /<td>([^\<]+)<\/td>/i );
			  break;
		  }
	  }

	  var village_id = location.href.replace(/(.+)=(\d+)$/gi, "$2");

	  var village_coords = (tmp && tmp[1]) ? tmp[1] : null;
	  if(village_coords == null) return;
	  village_coords = village_coords.replace(/\|/, "x");

	  var village_coords = village_coords.split("x");
	  xpathGetFirst("/html/body/table[3]/tbody/tr/td").innerHTML += plugins.quickattack.get_rallypoint_html(personals.getCurrentVillage(), village_coords[0], village_coords[1]);
  }
	};